package com.bite.common.core.utils;


import com.bite.common.core.constants.JwtConstants;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import java.util.HashMap;
import java.util.Map;
public class JwtUtils {
    /**
     * ⽣成令牌
     *
     * @param claims 数据
     * @param secret 密钥
     * @return 令牌
     */
    public static String createToken(Map<String, Object> claims, String secret)
    {
        String token =
                Jwts.builder().setClaims(claims).signWith(SignatureAlgorithm.HS512,
                        secret).compact();
        return token;
    }
    /**
     * 从令牌中获取数据
     *
     * @param token 令牌
     * @param secret 密钥
     * @return 数据
     */
    public static Claims parseToken(String token, String secret) {
        return
                Jwts.parser().setSigningKey(secret).parseClaimsJws(token).getBody();
    }


    public static void main(String[] args) {
        String secret = "fhioaufhioasfhaa";
        Map<String,Object> claims = new HashMap<>();
        claims.put("userId",1234546789L);
        System.out.println(createToken(claims, secret));
        String token = "eyJhbGciOiJIUzUxMiJ9.eyJ1c2VySWQiOjEyMzQ1NDY3ODl9.5DwK6vM3EQ9PWd50SZRlahzl30mQ__kqkodHF9f8PUsCLi9CLn72B1lhU4FXTvzvCUVjvvEGptCBVVgVlS_EGw";
        Claims claims1 = parseToken(token, secret);
        System.out.println(claims1);

    }

    public static String getUserKey(Claims claims) {
        Object value = claims.get(JwtConstants.LOGIN_USER_KEY);
        return getString(value);
    }

    public static String getUserId(Claims claims) {
        Object value = claims.get(JwtConstants.LOGIN_USER_ID);
        return getString(value);
    }

    private static String getString(Object value) {
        if(value == null) {
            return "";
        }
        return value.toString();
    }


}

